<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\facade\WeChat;
use app\common\model\User;
use app\common\model\UserThird;
use app\common\tool\Result;
use think\exception\ValidateException;
use think\facade\Cache;
use think\Response;

class Login extends Base
{
    public function login(): Response
    {
        try {
            $param = $this->request->post();

            $type = $param['type'] ?? 'account';
            if(!in_array($type,['account', 'face', 'finger', 'code'])){
                return Result::fail('不支持的登录类型！');
            }

            /*$v = validate('Login');
            if (!$this->scene($type)->check($param)) {
                return Result::fail($v->getError());
            }*/

            try {
                $this->validate($param, 'Login.'.$type);
            } catch (ValidateException $e) {
                return Result::fail($e->getError());
            }

            if($type == 'code'){
                $code = Cache::get('yusheng250124:'.$param['mobile']);
                if($code != $param['code']){
                    return Result::fail('验证码错误！');
                }
                $user = User::where('mobile', trim($param['mobile']))->where('is_del', 0)->find();
            }else{
                $user = User::where('account|mobile', trim($param['account']))->where('is_del', 0)->find();
            }
            if (empty($user)) {
                return Result::fail('账号不存在！');
            }
            if ($type == 'account' && $user->password != md5($param['password'])) {
                return Result::fail('密码错误！');
            }
            if ($user->is_lock == 1) {
                return Result::fail('账号已被限制登录！');
            }

            list($alert, $self_amount, $share_amount) = $this->loginTip($user);
            $token = $user->id == 1? '8a62a34d7a39ee0d4d9c8ef5c2e24494': md5(json_encode($param) . $this->request->ip() . time());
            $user->last_time = time();
            $user->last_ip = $this->request->ip();
            $user->token = $token;
            $user->registration_id = $param['registration_id']??'';
            $user->save();
            return Result::success('登录成功', ['token' => $token, 'alert'=>$alert, 'self_amount'=>$self_amount, 'share_amount'=>$share_amount]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    public function third(): Response
    {
        try{
            $param = $this->request->post();
            try {
                $this->validate($param, 'Third');
            } catch (ValidateException $e) {
                return Result::fail($e->getError());
            }
            if(!in_array($param['type'],['wechat', 'alipay'])){
                return Result::fail('不支持的登录类型！');
            }

            $third = UserThird::where(['type'=>$param['type'], 'openid'=>$param['openid'], 'is_del'=>0])->find();
            if(!$third){
                return Result::fastReturn(['code'=>301, 'msg'=>'请绑定手机号！', 'data'=>['url'=>'login/thirdBind']]);
            }

            $user = User::find($third->uid);

            if ($user->is_lock == 1) {
                return Result::fail('账号已被限制登录！');
            }

            $ip = request()->ip();
            $token = $user->id == 1? '8a62a34d7a39ee0d4d9c8ef5c2e24494': md5(json_encode($param) . $ip . time());
            $user->last_time = time();
            $user->last_ip = $ip;
            $user->token = $token;
            $user->save();

            list($alert, $self_amount, $share_amount) = $this->loginTip($user);
            return Result::success('登录成功', ['token' => $user->token, 'alert'=>$alert, 'self_amount'=>$self_amount, 'share_amount'=>$share_amount]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    public function thirdBind()
    {
        try{
            $param = $this->request->post();
            try {
                $this->validate($param, 'ThirdBind');
            } catch (ValidateException $e) {
                return Result::fail($e->getError());
            }
            if(!in_array($param['type'],['wechat', 'alipay'])){
                return Result::fail('不支持的登录类型！');
            }
            $code = Cache::get('yusheng250124:'.$param['mobile']);
            if($code != $param['code']){
                //return Result::fail('验证码错误！');
            }

            $param['ip'] = $this->request->ip();
            $result = User::_thirdSave($param);
            if($result['code'] != 1){
                return Result::fail('登录失败');
            }
            $user = $result['data']['user'];
            list($alert, $self_amount, $share_amount) = $this->loginTip($user);
            return Result::success('登录成功', ['token' => $user->token, 'alert'=>$alert, 'self_amount'=>$self_amount, 'share_amount'=>$share_amount]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    private function loginTip($user)
    {
        $alert = '';
        $self_amount = $share_amount = 0;
        if(!$user->token || !$user->last_time){
            $currency_register = Cache::get('system')['currency_register'];
            $currency_share = Cache::get('system')['currency_share'];
            $alert = "";

            $self_amount = $currency_register;
            $share_amount = $currency_share;
        }

        return [$alert, $self_amount, $share_amount];
    }

    /**
     * 重置密码
     * @return Response
     */
    public function resetPassword(): Response
    {
        try{
            $param = $this->request->post();
            try {
                $this->validate($param, 'ResetPassword');
            } catch (ValidateException $e) {
                return Result::fail($e->getError());
            }
            if(!$user = User::where('mobile', $param['mobile'])->find()){
                return Result::fail('手机号不存在！');
            }
            $code = Cache::get('yusheng250124:'.$param['mobile']);
            if($code != $param['code']){
                return Result::fail('验证码错误！');
            }
            $user->password = md5($param['password']);
            $user->save();
            return Result::success('重置成功');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    public function wechat()
    {
        $token = $this->request->param('token');
        if (!empty($token)) {
            $user = \app\common\model\User::where('token', $token)->find();
            if ($user) {
                $url = WeChat::withConfig(config('pay')['wx_pub'])->getOauthRedirect('https://' . $_SERVER['SERVER_NAME'] . '/api/login/wechat_open', $token);
                header("Location:" . $url);
                exit;
            }
            exit;
        }
    }

    public function wechat_open()
    {
        $token = $this->request->param('state', '');
        $code = $this->request->param('code', '');
        //创建接口实例
        $result = WeChat::withConfig(config('pay')['wx_pub'])->getOauthAccessToken($code);
        $user = \app\common\model\User::where('token', $token)->find();
        \app\common\model\User::where('token', $token)->update(['gzh_openid' => $result['openid']]);
        exit;
    }
}
